package com.mdd.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.UserFriend;
import com.mdd.common.entity.distribution.Distribution;
import com.mdd.common.entity.server.Sys;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.UserFriendMapper;
import com.mdd.common.mapper.distribution.DistributionMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.front.service.IReferrerService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.reference.ReferenceCollectValidate;
import com.mdd.front.vo.reference.ReferenceListVo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 我的推荐人实现类
 */
@Service
public class ReferrerServiceImpl implements IReferrerService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserFriendMapper userFriendMapper;

    @Resource
    private DistributionMapper distributionMapper;

    @Override
    public PageResult<ReferenceListVo> list(PageValidate pageValidate, ReferenceCollectValidate referenceCollectValidate,Integer userId) {
        Integer pageNo = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();
        HashMap<String, Object> resultMap = new HashMap<>();

        //已注册人数
        Long registeredCount = userMapper.selectCount(new QueryWrapper<User>().eq("inviter_id", userId));


        //未注册人数
        Long unregisteredCount = userFriendMapper.selectCount(new QueryWrapper<UserFriend>()
                .eq("uid", userId)
                .ne("user_id", null));


        //总人数
        long sumCount=registeredCount+unregisteredCount;

        resultMap.put("registeredCount",registeredCount);
        resultMap.put("unregisteredCount",unregisteredCount);
        resultMap.put("sumCount",sumCount);


        if(referenceCollectValidate.getType()==1){//注册用户
            // 查询出当前用户下面的一级用户
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.select("id,sn,avatar,real_name,nickname,username,mobile,money,is_new,code,earnings,create_time");
            //userQueryWrapper.eq("inviter_id", userId);
            userQueryWrapper.eq("first_leader", userId);

            if(!StringUtils.isEmpty(referenceCollectValidate.getContent())){
                userQueryWrapper .like("nickname", referenceCollectValidate.getContent()).or()
                                 .like("mobile", referenceCollectValidate.getContent());
            }

            Page<User> iPage = userMapper.selectPage(new Page<>(pageNo, pageSize), userQueryWrapper);
            List<ReferenceListVo> list = new ArrayList<>();
            for (User vo : iPage.getRecords()) {
                ReferenceListVo referenceListVo = new ReferenceListVo();
                BeanUtils.copyProperties(vo,referenceListVo);

                //查询当前用户是否是经销商
                Distribution distributionOne = distributionMapper.selectOne(new MPJQueryWrapper<Distribution>()
                        .select("t.level_id,t.is_distribution,dl.name as level_name")
                        .leftJoin("?_distribution_level dl ON dl.id = t.level_id".replace("?_", GlobalConfig.tablePrefix))
                        .eq("t.user_id", vo.getId()));
                /*System.out.println("vo id"+ vo.getId());
                System.out.println("distributionOne id"+ distributionOne.getId() + "level" + distributionOne.getLevelId());*/
                if(distributionOne!=null){
                    referenceListVo.setIsDistribution(distributionOne.getIsDistribution());
                    referenceListVo.setLevelId(distributionOne.getLevelId());
                    referenceListVo.setIsRegister(0);
                    if(distributionOne.getIsDistribution()==0){
                        referenceListVo.setLevelName("用户");
                    }else {
                        referenceListVo.setLevelName(distributionOne.getLevelName());
                    }
                }
                referenceListVo.setAvatar(UrlUtils.toAbsoluteUrl(vo.getAvatar()));
                referenceListVo.setCreateTime(TimeUtils.timestampToDate(vo.getCreateTime()));
                list.add(referenceListVo);
            }
            return PageResult.iPageHandle(iPage.getTotal(),iPage.getCurrent(),iPage.getSize(),list,resultMap);

        }else {
            //查询备忘录数据
            QueryWrapper<UserFriend> userFriendQueryWrapper = new QueryWrapper<>();
            userFriendQueryWrapper.eq("uid", userId);
            userFriendQueryWrapper.ne("user_id", null);
            userFriendQueryWrapper.select("id,head_pic as avatar,name as real_name,name as nickname,phone as mobile,is_new,code,earnings,create_time");

            if(!StringUtils.isEmpty(referenceCollectValidate.getContent())){
                userFriendQueryWrapper.like("name", referenceCollectValidate.getContent()).or()
                                      .like("phone", referenceCollectValidate.getContent());
            }

            Page<UserFriend> iPage = userFriendMapper.selectPage(new Page<>(pageNo, pageSize),userFriendQueryWrapper);
            List<ReferenceListVo> list = new ArrayList<>();
            for (UserFriend vo : iPage.getRecords()) {
                ReferenceListVo referenceListVo = new ReferenceListVo();
                BeanUtils.copyProperties(vo,referenceListVo);
                //查询当前用户是否是经销商
                Distribution distributionOne = distributionMapper.selectOne(new MPJQueryWrapper<Distribution>()
                        .select("t.level_id,t.is_distribution,dl.name as level_name")
                        .leftJoin("?_distribution_level dl ON dl.id = t.level_id".replace("?_", GlobalConfig.tablePrefix))
                        .eq("t.user_id", userId));
                if(distributionOne!=null){
                    referenceListVo.setIsDistribution(distributionOne.getIsDistribution());
                    referenceListVo.setLevelId(distributionOne.getLevelId());
                    referenceListVo.setIsRegister(0);
                    if(distributionOne.getIsDistribution()==0){
                        referenceListVo.setLevelName("用户");
                    }else {
                        referenceListVo.setLevelName(distributionOne.getLevelName());
                    }

                }
                referenceListVo.setAvatar(UrlUtils.toAbsoluteUrl(vo.getHeadPic()));
                referenceListVo.setCreateTime(TimeUtils.timestampToDate(vo.getCreateTime()));
                list.add(referenceListVo);
            }


            return PageResult.iPageHandle(iPage.getTotal(),iPage.getCurrent(),iPage.getSize(),list,resultMap);
        }

    }



}
